package cn.bs.seckill.rabbitMQ;

import cn.bs.seckill.pojo.SeckillMessage;
import cn.bs.seckill.pojo.SeckillOrders;
import cn.bs.seckill.pojo.User;
import cn.bs.seckill.service.GoodsService;
import cn.bs.seckill.service.OrdersService;
import cn.bs.seckill.utils.RedisUtil;
import cn.bs.seckill.vo.GoodsVo;
import cn.bs.seckill.vo.RespBeanEnum;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class Receiver {
    @Autowired
    private Gson gson;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private OrdersService ordersService;

    @RabbitListener(queues = "我是广播队列一的消息")
    public void receive1(String msg) {
        log.info("cgb2109 :"+msg);
    }
    @RabbitListener(queues = "我是广播队列二的消息")
    public void receive2(String msg) {
        log.info("cgb2111:"+msg);
    }

    @RabbitListener(queues = "我是路由队列一的消息")
    public void receive3(String msg) {
        log.info("cgb2109 :"+msg);
    }
    @RabbitListener(queues = "我是路由队列二的消息")
    public void receive4(String msg) {
        log.info("cgb2111:"+msg);
    }

    @RabbitListener(queues = "我是主题队列一的消息")
    public void receive5(String msg) {
        log.info("cgb2109 :"+msg);
    }
    @RabbitListener(queues = "我是主题队列二的消息")
    public void receive6(String msg) {
        log.info("cgb2111:"+msg);
    }

    @RabbitListener(queues = "seckillQueue")
    public void receive7(String msg) {
        log.info("秒杀:"+msg);
        SeckillMessage seckillMessage = gson.fromJson(msg, SeckillMessage.class);
        Long goodId = seckillMessage.getGoodId();
        User user = seckillMessage.getUser();
        GoodsVo goodsVoByGoodsId = goodsService.findGoodsVoByGoodsId(goodId);
        //判断库存是否充足
        if (goodsVoByGoodsId.getStockCount()<1){
            return;
        }
        //判断用户是否重复购买
        SeckillOrders seckillOrder = (SeckillOrders) redisUtil.get("order:" + user.getId() + ":" + goodId);
        if (null != seckillOrder) {
            return ;
        }
        //下单
        ordersService.secKill(user,goodsVoByGoodsId);

    }
}
